/*
 * @(#)UserGroup.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.user.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.dbutils.DbUtils;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.dao.AbstractDAObject;
import com.dcivision.framework.dao.AbstractQuery;
import com.dcivision.framework.dao.SubQuery;
import com.dcivision.framework.web.AbstractSearchForm;
import com.dcivision.user.bean.UserGroup;

/**
  UserGroupDAObject.java

  This class is the data access bean for table "USER_GROUP".

  @author      Rollo Chan
  @company     DCIVision Limited
  @creation date   17/07/2003
  @version     $Revision: 1.30.2.1 $
*/

public class UserGroupDAObject extends AbstractDAObject {

  public static final String REVISION = "$Revision: 1.30.2.1 $";

  public static final String TABLE_NAME = "USER_GROUP";

  public static final String GROUP_NAME = "GROUP_NAME";
  public static final String ID = "ID";
  public static final String GROUP_DESC = "GROUP_DESC";

  public UserGroupDAObject(SessionContainer sessionContainer, Connection dbConn) {
    super(sessionContainer, dbConn);
  }

  protected void initDBSetting() {
    this.baseTableName = TABLE_NAME;
    this.vecDBColumn.add("ID");
    this.vecDBColumn.add("OWNER_USER_RECORD_ID");
    this.vecDBColumn.add("GROUP_TYPE");
    this.vecDBColumn.add("GROUP_NAME");
    this.vecDBColumn.add("GROUP_DESC");
    this.vecDBColumn.add("RECORD_STATUS");
    this.vecDBColumn.add("UPDATE_COUNT");
    this.vecDBColumn.add("CREATOR_ID");
    this.vecDBColumn.add("CREATE_DATE");
    this.vecDBColumn.add("UPDATER_ID");
    this.vecDBColumn.add("UPDATE_DATE");
  }

  protected synchronized AbstractBaseObject getByID(Integer id) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.ID = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, id);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        if (rs.next()) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          return(tmpUserGroup);
        } else {
          throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized List getList(AbstractSearchForm searchForm) throws ApplicationException {
    PreparedStatement preStat = null;
    PreparedStatement preStatCnt = null;
    ResultSet rs = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStat = new StringBuffer();
    StringBuffer sqlStatCnt = new StringBuffer();
    List result = new ArrayList();
    int totalNumOfRecord = 0;
    int rowLoopCnt = 0;
    int startOffset = TextUtility.parseInteger(searchForm.getCurStartRowNo());
    int pageSize = TextUtility.parseInteger(searchForm.getPageOffset());

    String groupType = ((com.dcivision.user.web.ListUserGroupForm)searchForm).getGroupType();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        // Form the WHERE clause for filtering.
        if (searchForm.isSearchable()) {
          String searchField = getSearchColumn(searchForm.getBasicSearchField());
          sqlStat.append("AND  " + searchField + " " + searchForm.getBasicSearchType() + " ? ");
        }

        //format the sql for any 'LIKE' statement contained
        sqlStat = this.getFormattedSQL(sqlStat.toString());

        // Form the ORDER clause for sorting.
        if (searchForm.isSortable()) {
          String sortAttribute = searchForm.getSortAttribute();
          if (sortAttribute.indexOf(".") < 0) {
            sortAttribute = "A." + sortAttribute;
          }
          sqlStat.append("ORDER BY " + sortAttribute + " " + searchForm.getSortOrder());
        }

        // Get total number of record return.
        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        this.setPrepareStatement(preStatCnt, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStatCnt, 2, groupType);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStatCnt, 3, searchKeyword);
        }
        rsCnt = preStatCnt.executeQuery();
        if (rsCnt.next()) {
          totalNumOfRecord = rsCnt.getInt(1);
        }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }

        // Retrieve the result in row basis.
        sqlStat = this.getSelectListSQL(sqlStat, startOffset, pageSize);
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, groupType);
        if (searchForm.isSearchable()) {
          String searchKeyword = this.getFormattedKeyword(searchForm.getBasicSearchKeyword(), searchForm.getBasicSearchType());
          this.setPrepareStatement(preStat, 3, searchKeyword);
        }
        rs = preStat.executeQuery();

        this.positionCursor(rs, startOffset, pageSize);

        while (rs.next() && rowLoopCnt<pageSize) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          tmpUserGroup.setRecordCount(totalNumOfRecord);
          tmpUserGroup.setRowNum(startOffset++);
          ++rowLoopCnt;
          result.add(tmpUserGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
        try { rsCnt.close(); } catch (Exception ignore) {} finally { rsCnt = null; }
        try { preStatCnt.close(); } catch (Exception ignore) {} finally { preStatCnt = null; }
      }
    }
  }

  protected synchronized List getList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));
        sqlStat.append("ORDER BY A.GROUP_NAME ASC " );
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        rs = preStat.executeQuery();
        while (rs.next()) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          result.add(tmpUserGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected void validateInsert(AbstractBaseObject obj) throws ApplicationException {
    UserGroup userGroup = (UserGroup)obj;
    StringBuffer sbSqlStat = new StringBuffer();
    PreparedStatement pstat = null;
    ResultSet rs = null;

    // Check duplicate user group name in the same group type.
    sbSqlStat.append("SELECT COUNT(*) ");
    sbSqlStat.append("FROM   USER_GROUP ");
    sbSqlStat.append("WHERE  GROUP_NAME = ? AND GROUP_TYPE = ? AND RECORD_STATUS = ? ");
    sbSqlStat.append(this.getIDFilterWhereClause(null));

    try {
      pstat = this.dbConn.prepareStatement(sbSqlStat.toString());
      this.setPrepareStatement(pstat, 1, userGroup.getGroupName());
      this.setPrepareStatement(pstat, 2, userGroup.getGroupType());
      this.setPrepareStatement(pstat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
      rs = pstat.executeQuery();
      if (rs.next() && rs.getInt(1)>0) {
        throw new ApplicationException(com.dcivision.user.UserErrorConstant.DUPLICATE_GROUP_NAME);
      }
    } catch (java.sql.SQLException sqle) {
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { pstat.close(); } catch (Exception ignore) {} finally { pstat = null; }
    }
  }

  protected void validateUpdate(AbstractBaseObject obj) throws ApplicationException {
    UserGroup userGroup = (UserGroup)obj;
    StringBuffer sbSqlStat = new StringBuffer();
    PreparedStatement pstat = null;
    ResultSet rs = null;

    // Check duplicate user group name in the same group type.
    sbSqlStat.append("SELECT COUNT(*) ");
    sbSqlStat.append("FROM   USER_GROUP ");
    sbSqlStat.append("WHERE  GROUP_NAME = ? AND GROUP_TYPE = ? AND RECORD_STATUS = ? AND ID <> ? ");
    sbSqlStat.append(this.getIDFilterWhereClause(null));

    try {
      pstat = this.dbConn.prepareStatement(sbSqlStat.toString());
      this.setPrepareStatement(pstat, 1, userGroup.getGroupName());
      this.setPrepareStatement(pstat, 2, userGroup.getGroupType());
      this.setPrepareStatement(pstat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);
      this.setPrepareStatement(pstat, 4, userGroup.getID());
      rs = pstat.executeQuery();
      if (rs.next() && rs.getInt(1)>0) {
        throw new ApplicationException(com.dcivision.user.UserErrorConstant.DUPLICATE_GROUP_NAME);
      }
    } catch (java.sql.SQLException sqle) {
      throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
    } finally {
      try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
      try { pstat.close(); } catch (Exception ignore) {} finally { pstat = null; }
    }
  }

  protected void validateDelete(AbstractBaseObject obj) throws ApplicationException {
  }

  protected synchronized AbstractBaseObject insert(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    UserGroup tmpUserGroup = (UserGroup)((UserGroup)obj).clone();

    synchronized(dbConn) {
      try {
        Integer nextID = getNextPrimaryID();
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("INSERT ");
        sqlStat.append("INTO   USER_GROUP(ID, OWNER_USER_RECORD_ID, GROUP_TYPE, GROUP_NAME, GROUP_DESC, RECORD_STATUS, UPDATE_COUNT, CREATOR_ID, CREATE_DATE, UPDATER_ID, UPDATE_DATE) ");
        sqlStat.append("VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, nextID);
        setPrepareStatement(preStat, 2, tmpUserGroup.getOwnerUserRecordID());
        setPrepareStatement(preStat, 3, tmpUserGroup.getGroupType());
        setPrepareStatement(preStat, 4, tmpUserGroup.getGroupName());
        setPrepareStatement(preStat, 5, tmpUserGroup.getGroupDesc());
        setPrepareStatement(preStat, 6, GlobalConstant.RECORD_STATUS_ACTIVE);
        setPrepareStatement(preStat, 7, new Integer(0));
        setPrepareStatement(preStat, 8, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 9, currTime);
        setPrepareStatement(preStat, 10, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 11, currTime);
        preStat.executeUpdate();
        tmpUserGroup.setID(nextID);
        tmpUserGroup.setCreatorID(sessionContainer.getUserRecordID());
        tmpUserGroup.setCreateDate(currTime);
        tmpUserGroup.setUpdaterID(sessionContainer.getUserRecordID());
        tmpUserGroup.setUpdateDate(currTime);
        tmpUserGroup.setUpdateCount(new Integer(0));
        tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
        tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
        return(tmpUserGroup);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_INSERT_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject update(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    UserGroup tmpUserGroup = (UserGroup)((UserGroup)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        Timestamp currTime = Utility.getCurrentTimestamp();
        sqlStat.append("UPDATE USER_GROUP ");
        sqlStat.append("SET  OWNER_USER_RECORD_ID=?, GROUP_TYPE=?, GROUP_NAME=?, GROUP_DESC=?, UPDATE_COUNT=?, UPDATER_ID=?, UPDATE_DATE=? ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpUserGroup.getOwnerUserRecordID());
        setPrepareStatement(preStat, 2, tmpUserGroup.getGroupType());
        setPrepareStatement(preStat, 3, tmpUserGroup.getGroupName());
        setPrepareStatement(preStat, 4, tmpUserGroup.getGroupDesc());
        setPrepareStatement(preStat, 5, new Integer(tmpUserGroup.getUpdateCount().intValue() + 1));
        setPrepareStatement(preStat, 6, sessionContainer.getUserRecordID());
        setPrepareStatement(preStat, 7, currTime);
        setPrepareStatement(preStat, 8, tmpUserGroup.getID());
        setPrepareStatement(preStat, 9, tmpUserGroup.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          tmpUserGroup.setUpdaterID(sessionContainer.getUserRecordID());
          tmpUserGroup.setUpdateDate(currTime);
          tmpUserGroup.setUpdateCount(new Integer(tmpUserGroup.getUpdateCount().intValue() + 1));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          return(tmpUserGroup);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_UPDATE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized AbstractBaseObject delete(AbstractBaseObject obj) throws ApplicationException {
    PreparedStatement preStat = null;
    StringBuffer sqlStat = new StringBuffer();
    UserGroup tmpUserGroup = (UserGroup)((UserGroup)obj).clone();

    synchronized(dbConn) {
      try {
        int updateCnt = 0;
        sqlStat.append("DELETE ");
        sqlStat.append("FROM   USER_GROUP ");
        sqlStat.append("WHERE  ID=? AND UPDATE_COUNT=? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        setPrepareStatement(preStat, 1, tmpUserGroup.getID());
        setPrepareStatement(preStat, 2, tmpUserGroup.getUpdateCount());
        updateCnt = preStat.executeUpdate();
        if (updateCnt == 0) {
          throw new ApplicationException(ErrorConstant.DB_CONCURRENT_ERROR);
        } else {
          return(tmpUserGroup);
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_DELETE_ERROR, e);
      } finally {
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  protected synchronized void auditTrail(String opMode, AbstractBaseObject obj) throws ApplicationException {
    Vector oldValues = new Vector();
    Vector newValues = new Vector();
    UserGroup tmpUserGroup = (UserGroup)this.oldValue;

    if (tmpUserGroup != null) {
      oldValues.add(toAuditTrailValue(tmpUserGroup.getID()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getOwnerUserRecordID()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getGroupType()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getGroupName()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getGroupDesc()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getRecordStatus()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getUpdateCount()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getCreatorID()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getCreateDate()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getUpdaterID()));
      oldValues.add(toAuditTrailValue(tmpUserGroup.getUpdateDate()));
    }

    tmpUserGroup = (UserGroup)obj;
    if (tmpUserGroup != null) {
      newValues.add(toAuditTrailValue(tmpUserGroup.getID()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getOwnerUserRecordID()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getGroupType()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getGroupName()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getGroupDesc()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getRecordStatus()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getUpdateCount()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getCreatorID()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getCreateDate()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getUpdaterID()));
      newValues.add(toAuditTrailValue(tmpUserGroup.getUpdateDate()));
    }

    auditTrailBase(opMode, oldValues, newValues);
  }

  /***********************************************************************
   * DON'T Modify the codes above unless you know what you are doing!!!  *
   * Put your own functions beblow.                                      *
   * For FINDER methods, the function name should be in the notation:    *
   *   public Object getObjectBy<Criteria>()                             *
   *   - e.g. public Object getObjectByCode()                            *
   *   public List getListBy<Criteria>()                                 *
   *   - e.g. public List getListByUserID()                              *
   * For OPERATION methods, the function name should be in the notation: *
   *   public void <Operation>ObjectBy<Criteria>()                       *
   *   - e.g. public void deleteObjectByCode()                           *
   *   public void <Operation>ListBy<Criteria>()                         *
   *   - e.g. public void deleteListByUserID()                           *
   ***********************************************************************/

  /**
   * getListByUserRecordIDGroupType
   *
   * Get the list of user group of a user record according to eh user record ID
   * and group type.
   *
   * @param userRecordID  The user record ID.
   * @param groupType     The group type.
   * @return              A list of user groups.
   * @throws              ApplicationException
   */
  public synchronized List getListByUserRecordIDGroupType(Integer userRecordID, String groupType) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A, MTM_USER_RECORD_USER_GROUP B ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? AND B.USER_RECORD_ID = ? AND A.ID = B.USER_GROUP_ID ");
        sqlStat.append(this.getIDFilterWhereClause("A"));

        // Retrieve the result in row basis.
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, groupType);
        this.setPrepareStatement(preStat, 3, userRecordID);
        rs = preStat.executeQuery();

        while (rs.next()) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          result.add(tmpUserGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * getListSQLByUserRecordIDGroupType
   * get the subQuery of user group of a user record according to eh user record ID
   * @param userRecordID
   * @param groupType
   * @return a subQuery of user group
   * @throws ApplicationException
   */
  public AbstractQuery getListSQLByUserRecordIDGroupType(Integer userRecordID, String groupType){
    AbstractQuery subQuery = new SubQuery();
    StringBuffer sqlStat = new StringBuffer();
 
        sqlStat.append("SELECT A.ID ");
        sqlStat.append("FROM   USER_GROUP A, MTM_USER_RECORD_USER_GROUP B ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? AND B.USER_RECORD_ID = ? AND A.ID = B.USER_GROUP_ID ");
        sqlStat.append(this.getIDFilterWhereClause("A"));
        subQuery.append(sqlStat.toString());
        // Retrieve the result in row basis.

        //this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        subQuery.setParameter(1, GlobalConstant.RECORD_STATUS_ACTIVE);
        //this.setPrepareStatement(preStat, 2, groupType);
        subQuery.setParameter(2,groupType);
        //this.setPrepareStatement(preStat, 3, userRecordID);
        subQuery.setParameter(3,userRecordID);
        
        
     return subQuery;
  }
  public AbstractQuery getListSQLByUserRecordIDsGroupType(List userRecordIDs, String groupType){
    AbstractQuery subQuery = new SubQuery();
    StringBuffer sqlStat = new StringBuffer();
 
        sqlStat.append("SELECT A.ID ");
        sqlStat.append("FROM   USER_GROUP A, MTM_USER_RECORD_USER_GROUP B ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? ");
        sqlStat.append(" AND ( ");
        for(int i=0;i<userRecordIDs.size();i++){
          if(i==0){
            sqlStat.append(" B.USER_RECORD_ID = ? ");
          }else{
            sqlStat.append(" OR B.USER_RECORD_ID = ? ");
          }
        }
        sqlStat.append(" )");
        sqlStat.append(" AND A.ID = B.USER_GROUP_ID ");
        sqlStat.append(this.getIDFilterWhereClause("A"));
        subQuery.append(sqlStat.toString());
        // Retrieve the result in row basis.

       
        subQuery.setParameter(1, GlobalConstant.RECORD_STATUS_ACTIVE);
       
        subQuery.setParameter(2,groupType);
       for(int y=0;y<userRecordIDs.size();y++){
          subQuery.setParameter(y+3,userRecordIDs.get(y));
       }
        
     subQuery.pack();   
     return subQuery;
  }
  /**
   * Return the array of string[] to show the permission of groups.<br>
   * [0] User Group ID<br>
   * [1] Group Name<br>
   * [2] Subject Type(Should be "G")<br>
   * [3] Permission String<br>
   * [4] Start Time<br>
   * [5] End Time<br>
   * [6] Permission must flag<br>
   * [7] Permimssion ID<br>
   *
   * @param objType
   * @param objID
   * @return
   * @throws ApplicationException
   */
  public synchronized String[][] getHasPermissionArrayByObjectTypeObjectID(String objType, Integer objID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, B.PERMISSION, B.MUST_FLAG, B.START_TIME, B.END_TIME, B.ID AS PERM_ID ");
        sqlStat.append("FROM   USER_GROUP A, USER_GROUP_PERMISSION B ");
        sqlStat.append("WHERE  A.ID > 0 AND A.ID = B.USER_GROUP_ID AND A.RECORD_STATUS = ? AND B.RECORD_STATUS = ? AND B.OBJECT_TYPE = ? AND B.OBJECT_ID = ? AND A.GROUP_TYPE = ? ");
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, objType);
        this.setPrepareStatement(preStat, 4, objID);
        this.setPrepareStatement(preStat, 5, UserGroup.GROUP_TYPE_PUBLIC);
        rs = preStat.executeQuery();
        while (rs.next()) {
          String startTime = TextUtility.formatDate(getResultSetTimestamp(rs, "START_TIME"), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
          String endTime = TextUtility.formatDate(getResultSetTimestamp(rs, "END_TIME"), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
          result.add(new String[] {getResultSetString(rs, "ID"), getResultSetString(rs, "GROUP_NAME"), GlobalConstant.SUBJECT_TYPE_GROUP, getResultSetString(rs, "PERMISSION"), startTime, endTime, (GlobalConstant.TRUE.equals(getResultSetString(rs, "MUST_FLAG")) ? GlobalConstant.TRUE : GlobalConstant.FALSE), getResultSetString(rs, "PERM_ID")});
        }
        String[][] tmpAry = new String[result.size()][];
        for (int i = 0; i < result.size(); i++) {
          tmpAry[i] = (String[])result.get(i);
        }
        return(tmpAry);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * Return the array of string[] to show the groups who have no permission.<br>
   * [0] User Group ID<br>
   * [1] Group Name<br>
   * [2] Subject Type(Should be "G")<br>
   * [3] Empty Permission String<br>
   * [4] Empty Start Time<br>
   * [5] Empty End Time<br>
   * [6] "N" for initial must flag<br>
   * [7] "-1" for new permimssion ID<br>
   *
   * @param objType
   * @param objID
   * @return
   * @throws ApplicationException
   */
  public synchronized String[][] getHasNoPermissionArrayByObjectTypeObjectID(String objType, Integer objID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    String[][] hasAry = this.getHasPermissionArrayByObjectTypeObjectID(objType, objID);

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.ID > 0 AND A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? ");
        if (hasAry.length > 0) {
          sqlStat.append("AND (");
          for (int i = 0; i < hasAry.length; i++) {
            sqlStat.append(" A.ID <> ");
            sqlStat.append(hasAry[i][0]);
            sqlStat.append(" AND");
          }
          sqlStat.delete(sqlStat.length()-3, sqlStat.length());
          sqlStat.append(") ");
        }
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, UserGroup.GROUP_TYPE_PUBLIC);
        rs = preStat.executeQuery();
        while (rs.next()) {
          result.add(new String[] {getResultSetString(rs, "ID"), getResultSetString(rs, "GROUP_NAME"), GlobalConstant.SUBJECT_TYPE_GROUP, "", "", "", GlobalConstant.FALSE, "-1"});
        }
        String[][] tmpAry = new String[result.size()][];
        for (int i = 0; i < result.size(); i++) {
          tmpAry[i] = (String[])result.get(i);
        }
        return(tmpAry);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized List getPublicGroupList() throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, UserGroup.GROUP_TYPE_PUBLIC);
        rs = preStat.executeQuery();
        while (rs.next()) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          result.add(tmpUserGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public synchronized List getPrivateGroupList() throws ApplicationException {
    return this.getPrivateGroupList(this.sessionContainer.getUserRecordID());
  }

  public synchronized List getPrivateGroupList(Integer userRecordID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? AND A.OWNER_USER_RECORD_ID = ? ");
        sqlStat.append(this.getIDFilterWhereClause("A"));
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, UserGroup.GROUP_TYPE_PRIVATE);
        this.setPrepareStatement(preStat, 3, userRecordID);
        rs = preStat.executeQuery();
        while (rs.next()) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          result.add(tmpUserGroup);
        }
        return(result);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * Return the array of string[] to show the permission of groups.<br>
   * [0] User Group ID<br>
   * [1] Group Name<br>
   * [2] Subject Type(Should be "G")<br>
   * [3] Permission String<br>
   * [4] Start Time<br>
   * [5] End Time<br>
   * [6] Permission must flag<br>
   * [7] Permimssion ID<br>
   * [8] Updater full name 
   *
   * @param objType
   * @param objID
   * @return
   * @throws ApplicationException
   */
  public synchronized String[][] getHasPermissionAndUpdaterArrayByObjectTypeObjectID(String objType, Integer objID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME, B.PERMISSION, B.MUST_FLAG, B.START_TIME, B.END_TIME, B.ID AS PERM_ID ,C.FULL_NAME AS UPDATER_FULL_NAME ");
        sqlStat.append("FROM   USER_GROUP A, USER_GROUP_PERMISSION B ,USER_RECORD C ");
        sqlStat.append("WHERE  A.ID > 0 AND A.ID = B.USER_GROUP_ID  AND C.ID = B.UPDATER_ID AND A.RECORD_STATUS = ? AND B.RECORD_STATUS = ? AND B.OBJECT_TYPE = ? AND B.OBJECT_ID = ? AND A.GROUP_TYPE = ? ");
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 3, objType);
        this.setPrepareStatement(preStat, 4, objID);
        this.setPrepareStatement(preStat, 5, UserGroup.GROUP_TYPE_PUBLIC);
        rs = preStat.executeQuery();
        while (rs.next()) {
          String startTime = TextUtility.formatDate(getResultSetTimestamp(rs, "START_TIME"), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
          String endTime = TextUtility.formatDate(getResultSetTimestamp(rs, "END_TIME"), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
          result.add(new String[] {getResultSetString(rs, "ID"), getResultSetString(rs, "GROUP_NAME"), GlobalConstant.SUBJECT_TYPE_GROUP, getResultSetString(rs, "PERMISSION"), startTime, endTime, (GlobalConstant.TRUE.equals(getResultSetString(rs, "MUST_FLAG")) ? GlobalConstant.TRUE : GlobalConstant.FALSE), getResultSetString(rs, "PERM_ID")
                ,getResultSetString(rs, "UPDATER_FULL_NAME")});
        }
        String[][] tmpAry = new String[result.size()][];
        for (int i = 0; i < result.size(); i++) {
          tmpAry[i] = (String[])result.get(i);
        }
        return(tmpAry);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  /**
   * Return the array of string[] to show the groups who have no permission.<br>
   * [0] User Group ID<br>
   * [1] Group Name<br>
   * [2] Subject Type(Should be "G")<br>
   * [3] Empty Permission String<br>
   * [4] Empty Start Time<br>
   * [5] Empty End Time<br>
   * [6] "N" for initial must flag<br>
   * [7] "-1" for new permimssion ID<br>
   * [8] Updater full name
   * 
   * @param objType
   * @param objID
   * @return
   * @throws ApplicationException
   */
  public synchronized String[][] getHasNoPermissionAndUpdaterArrayByObjectTypeObjectID(String objType, Integer objID) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    List result = new ArrayList();
    String[][] hasAry = this.getHasPermissionAndUpdaterArrayByObjectTypeObjectID(objType, objID);

    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.ID > 0 AND A.RECORD_STATUS = ? AND A.GROUP_TYPE = ? ");
        if (hasAry.length > 0) {
          sqlStat.append("AND (");
          for (int i = 0; i < hasAry.length; i++) {
            sqlStat.append(" A.ID <> ");
            sqlStat.append(hasAry[i][0]);
            sqlStat.append(" AND");
          }
          sqlStat.delete(sqlStat.length()-3, sqlStat.length());
          sqlStat.append(") ");
        }
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, GlobalConstant.RECORD_STATUS_ACTIVE);
        this.setPrepareStatement(preStat, 2, UserGroup.GROUP_TYPE_PUBLIC);
        rs = preStat.executeQuery();
        while (rs.next()) {
          result.add(new String[] {getResultSetString(rs, "ID"), getResultSetString(rs, "GROUP_NAME"), GlobalConstant.SUBJECT_TYPE_GROUP, "", "", "", GlobalConstant.FALSE, "-1"});
        }
        String[][] tmpAry = new String[result.size()][];
        for (int i = 0; i < result.size(); i++) {
          tmpAry[i] = (String[])result.get(i);
        }
        return(tmpAry);
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  } 
  
  public AbstractBaseObject getObjectByGroupName(String groupName) throws ApplicationException {
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    
    synchronized(dbConn) {
      try {
        sqlStat.append("SELECT A.ID, A.OWNER_USER_RECORD_ID, A.GROUP_TYPE, A.GROUP_NAME, A.GROUP_DESC, A.RECORD_STATUS, A.UPDATE_COUNT, A.CREATOR_ID, A.CREATE_DATE, A.UPDATER_ID, A.UPDATE_DATE ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.GROUP_NAME = ? AND A.GROUP_TYPE = ? AND A.RECORD_STATUS = ? ");
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        this.setPrepareStatement(preStat, 1, groupName);
        this.setPrepareStatement(preStat, 2, UserGroup.GROUP_TYPE_PUBLIC);
        this.setPrepareStatement(preStat, 3, GlobalConstant.RECORD_STATUS_ACTIVE);        
        rs = preStat.executeQuery();
        //if (rs.next()) {
        if (rs.next() && rs.getInt(1)>0) {
          UserGroup tmpUserGroup = new UserGroup();
          tmpUserGroup.setID(getResultSetInteger(rs, "ID"));
          tmpUserGroup.setOwnerUserRecordID(getResultSetInteger(rs, "OWNER_USER_RECORD_ID"));
          tmpUserGroup.setGroupType(getResultSetString(rs, "GROUP_TYPE"));
          tmpUserGroup.setGroupName(getResultSetString(rs, "GROUP_NAME"));
          tmpUserGroup.setGroupDesc(getResultSetString(rs, "GROUP_DESC"));
          tmpUserGroup.setRecordStatus(getResultSetString(rs, "RECORD_STATUS"));
          tmpUserGroup.setUpdateCount(getResultSetInteger(rs, "UPDATE_COUNT"));
          tmpUserGroup.setCreatorID(getResultSetInteger(rs, "CREATOR_ID"));
          tmpUserGroup.setCreateDate(getResultSetTimestamp(rs, "CREATE_DATE"));
          tmpUserGroup.setUpdaterID(getResultSetInteger(rs, "UPDATER_ID"));
          tmpUserGroup.setUpdateDate(getResultSetTimestamp(rs, "UPDATE_DATE"));
          tmpUserGroup.setCreatorName(UserInfoFactory.getUserFullName(tmpUserGroup.getCreatorID()));
          tmpUserGroup.setUpdaterName(UserInfoFactory.getUserFullName(tmpUserGroup.getUpdaterID()));
          return(tmpUserGroup);
        } else {
          //throw new ApplicationException(ErrorConstant.DB_RECORD_NOT_FOUND_ERROR);
      	  return null;
        }
      } catch (ApplicationException appEx) {
        throw appEx;
      } catch (SQLException sqle) {
        log.error(sqle, sqle);
        throw new ApplicationException(ErrorConstant.DB_GENERAL_ERROR, sqle, sqle.toString());
      } catch (Exception e) {
        log.error(e, e);
        throw new ApplicationException(ErrorConstant.DB_SELECT_ERROR, e);
      } finally {
        try { rs.close(); } catch (Exception ignore) {} finally { rs = null; }
        try { preStat.close(); } catch (Exception ignore) {} finally { preStat = null; }
      }
    }
  }

  public List getGroupList(){
    List result = new ArrayList();
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    
    try {
      synchronized (dbConn) {
        sqlStat.append("SELECT A.ID, A.GROUP_NAME ");
        sqlStat.append("FROM   USER_GROUP A ");
        sqlStat.append("WHERE  A.RECORD_STATUS = 'A' ");
        sqlStat.append("ORDER BY A.GROUP_NAME ASC ");
        preStat = dbConn.prepareStatement(sqlStat.toString());
        rs = preStat.executeQuery();
        while (rs.next()){
          List tempRecord = new ArrayList();
          tempRecord.add(rs.getString("ID"));
          tempRecord.add(rs.getString("GROUP_NAME"));
          result.add(tempRecord);
        }
        return result;
      }
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
    } catch (Exception e) {
      log.error(e, e);
    } finally {
      try {
        rs.close();
      } catch (Exception ignore) {} finally {
        rs = null;
      }
      try {
        preStat.close();
      } catch (Exception ignore) {} finally {
        preStat = null;
      }
    }
    return null;
  }
  
  public List getGroupRecordsAndPageInfo (
      String searchGroupName ,
      String startOffset ,
      String pageSize ,
      String orderBy ,
      String req
  ) {
    List result = new ArrayList();
    PreparedStatement preStat = null;
    ResultSet rs = null;
    StringBuffer sqlStat = new StringBuffer();
    PreparedStatement preStatCnt = null;
    ResultSet rsCnt = null;
    StringBuffer sqlStatCnt = null;
    String cnt = null;
    
    if (Utility.isEmpty(orderBy)){
      orderBy = this.GROUP_NAME;
      req = "ASC";
    }

    try {
      synchronized (dbConn) {
        sqlStat.append("SELECT ID, GROUP_NAME, GROUP_DESC ");
        sqlStat.append("FROM USER_GROUP ");
        sqlStat.append("WHERE RECORD_STATUS = 'A' ");
        if (!Utility.isEmpty(searchGroupName)) {
          sqlStat.append(" AND GROUP_NAME LIKE '%" + searchGroupName + "%' ");
        }
        sqlStat.append("ORDER BY " + orderBy + " " + req);

        sqlStatCnt = this.getSelectCountSQL(sqlStat);
        preStatCnt = dbConn.prepareStatement(sqlStatCnt.toString());
        rsCnt = preStatCnt.executeQuery();
        rsCnt = preStatCnt.executeQuery();
        while(rsCnt.next()){
          cnt = rsCnt.getString(1);
        }

        sqlStat = this.getSelectListSQL(sqlStat, Integer.parseInt(startOffset), Integer.parseInt(pageSize));
        preStat = dbConn.prepareStatement(sqlStat.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
        rs = preStat.executeQuery();
        int rowLoopCnt = 0;
        while (rs.next() && rowLoopCnt < Integer.parseInt(pageSize)) {
          List tempRecord = new ArrayList();
          tempRecord.add(rs.getString(this.ID));
          tempRecord.add(rs.getString(this.GROUP_NAME));
          tempRecord.add(rs.getString(this.GROUP_DESC));
          ++rowLoopCnt;
          result.add(tempRecord);
        }
        StringBuffer pageInfomation = new StringBuffer();
        pageInfomation.append("startOffset:" + startOffset + ";");
        pageInfomation.append("pageSize:" + pageSize + ";");
        pageInfomation.append("orderBy:" + orderBy + ";");
        pageInfomation.append("req:" + req + ";");
        pageInfomation.append("total:" + cnt + "");
        result.add(pageInfomation.toString());
        return result;
      }
    } catch (SQLException sqle) {
      log.error(sqle, sqle);
    } catch (Exception e) {
      log.error(e, e);
    } finally {  
      DbUtils.closeQuietly(rs); 
      DbUtils.closeQuietly(preStat); 
      DbUtils.closeQuietly(rsCnt); 
      DbUtils.closeQuietly(preStatCnt); 
    }
    return null;
  }
}
